from django.db import models
import datetime
from django.utils import timezone

# Create your models here.

class Category(models.Model):
    name = models.CharField(max_length=64, verbose_name='分类')

    class Meta:
        db_table = 't_category'  # 指明数据库表名
        verbose_name = '分类'  # 在admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "name": self.name
        }
        return resp_dict

    def __str__(self):
        return self.name


class Blogs(models.Model):
    # id = models.AutoField(primary_key=True, db_index=True)
    title = models.CharField(max_length=254, verbose_name='标题', db_index=True, unique=True)
    digest = models.CharField(max_length=512, verbose_name='摘要')
    clicks = models.IntegerField(default=0, verbose_name='阅读量')
    source = models.CharField(max_length=64, verbose_name='来源')
    index_image_url = models.CharField(max_length=256, verbose_name='图片链接地址')
    content = models.TextField(verbose_name='内容主体')
    create_time = models.DateTimeField(default=timezone.now, db_index=True)
    category = models.ForeignKey(Category)

    class Meta:
        db_table = 'toutiao01'  # 指明数据库表名
        verbose_name = '头条'  # 在admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    """在admin站点显示的名字"""

    def __str__(self):
        return self.title

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            "digest": self.digest,
            "create_time": (self.create_time).strftime("%Y-%m-%d %H:%M:%S"),
            "clicks": self.clicks,
            "index_image_url": self.index_image_url,
            'source': self.source
        }
        return resp_dict

    def to_show(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            # "digest": self.digest,
            "create_time": (self.create_time).strftime("%Y-%m-%d %H:%M:%S"),
            "content": self.content,
            "clicks": self.clicks,
            # "index_image_url": self.index_image_url,
            'source': self.source
        }
        return resp_dict

    def get_time(self):

        return (self.create_time).strftime("%Y-%m-%d %H:%M:%S")

    # 自定义在管理界面的显示
    def pub_date(self):
        return self.create_time.strftime('%Y年%m月%d日')

    pub_date.short_description = '发布日期'
    pub_date.admin_order_field = 'create_time'
